package com.ruoyi.device.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PrimaryKeyIdUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.customer.domain.CustomerDeviceBindVO;
import com.ruoyi.device.domain.Device;
import com.ruoyi.device.domain.DeviceAccount;
import com.ruoyi.device.domain.ImportResult;
import com.ruoyi.device.mapper.DeviceMapper;
import com.ruoyi.device.service.IDeviceService;
import com.ruoyi.device.utils.QRCodeUtils;
import com.ruoyi.system.api.domain.SysFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 设备管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-03
 */
@Service
public class DeviceServiceImpl implements IDeviceService 
{
    private static final Logger log = LoggerFactory.getLogger(DeviceServiceImpl.class);
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectDeviceById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDevice(Device device)
    {
        device.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        device.setCreateTime(DateUtils.getNowDate());
        int rows = deviceMapper.insertDevice(device);
        insertDeviceAccount(device);
        return rows;
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDevice(Device device)
    {
        device.setUpdateTime(DateUtils.getNowDate());
        deviceMapper.deleteDeviceAccountByDeviceId(device.getId());
        insertDeviceAccount(device);
        return deviceMapper.updateDevice(device);
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        deviceMapper.deleteDeviceAccountByDeviceIds(ids);
        return deviceMapper.deleteDeviceByIds(ids);
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDeviceById(Long id)
    {
        deviceMapper.deleteDeviceAccountByDeviceId(id);
        return deviceMapper.deleteDeviceById(id);
    }

    @Override
    public Long selectDeviceByNo(String deviceNo) {
        return deviceMapper.getDeviceIdByNo(deviceNo);
    }

    @Override
    public List<CustomerDeviceBindVO> selectCustomerDeviceBindList(CustomerDeviceBindVO customerDeviceBind) {
        return deviceMapper.selectCustomerDeviceBindList(customerDeviceBind);
    }

    @Override
    public Device selectDeviceByDeviceNo(String deviceNo) {
        return deviceMapper.selectDeviceByDeviceNo(deviceNo);
    }

    @Override
    public ImportResult importDevice(List<SysFile> list,String deviceType) {
        List<String> errList = new ArrayList<>();
        List<Device> InsertList = new ArrayList<>();
        ImportResult importResult = new ImportResult();
        Date nowDate = DateUtils.getNowDate();
        for (SysFile file : list) {
            if(StringUtils.isNull(file.getUrl())){
                errList.add(file.getName());
                continue;
            }
            try {
                String text = QRCodeUtils.decodeQRCodeFromURL(file.getUrl());
                String deviceNo = QRCodeUtils.getDeviceNo(text);
                if(StringUtils.isNull(deviceNo)){
                    errList.add(file.getName());
                    continue;
                }
                if(errList.isEmpty()){
                    Device device = new Device();
                    device.setDeviceNo(deviceNo);
                    device.setCreateTime(nowDate);
                    device.setCreateBy(SecurityUtils.getUsername());
                    device.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
                    device.setType(deviceType);
                    device.setName(file.getName().split("_")[0]);
                    device.setQrCode(file.getUrl());
                    InsertList.add(device);
                }
            } catch (Exception e) {
                log.error("导入设备失败：{}",e.getMessage());
                errList.add(file.getName());
            }
        }
        if(!errList.isEmpty()){
            importResult.setCode("500");
            importResult.setMessage("导入失败");
            importResult.setErrList(errList);
            return importResult;
        }
        deviceMapper.batchInsertDevice(InsertList);
        importResult.setCode("200");
        importResult.setMessage("导入成功");
        return importResult;
    }


    /**
     * 新增设备账号信息信息
     * 
     * @param device 设备管理对象
     */
    public void insertDeviceAccount(Device device)
    {
        List<DeviceAccount> deviceAccountList = device.getDeviceAccountList();
        Long id = device.getId();
        if (StringUtils.isNotNull(deviceAccountList))
        {
            List<DeviceAccount> list = new ArrayList<DeviceAccount>();
            for (DeviceAccount deviceAccount : deviceAccountList)
            {
                deviceAccount.setDeviceId(id);
                list.add(deviceAccount);
            }
            if (list.size() > 0)
            {
                deviceMapper.batchDeviceAccount(list);
            }
        }
    }
}
